from django.contrib.auth.hashers import make_password
from django.core.validators import EmailValidator
from rest_framework import serializers

from rest_framework.validators import UniqueValidator

from exercise.models import QuestionGroup
from exercise.serializers import QuestionGroupSerializer
from user.models import ProjUser, ProjUserGroup


class RegisterSerializer(serializers.ModelSerializer):  # 用于注册的序列化器类
    # 用户名必须唯一
    username = serializers.CharField(max_length=150, validators=[UniqueValidator(queryset=ProjUser.objects.all())])
    # 邮箱必须合法且唯一
    email = serializers.EmailField(validators=[EmailValidator(), UniqueValidator(queryset=ProjUser.objects.all())])

    password = serializers.CharField(write_only=True)

    class Meta:
        model = ProjUser
        fields = ('username', 'password', 'email')  # 注册时只需要提交这三个字段就好

    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data.get('password'))
        return super().create(validated_data)

    def update(self, instance, validated_data):
        password = validated_data.pop('password', None)
        if password is not None:
            instance.password = make_password(password)
        super().update(instance=instance, validated_data=validated_data)
        return instance


class ProjUserGroupListSerializer(serializers.ModelSerializer):
    name = serializers.ReadOnlyField()
    creator = serializers.ReadOnlyField(source='creator.username')
    creat_time = serializers.ReadOnlyField()

    class Meta:
        model = ProjUserGroup
        fields = ('id', 'name', 'creator', 'creat_time', )


class GroupUserSerializer(serializers.ModelSerializer):
    """
    用户组详情序列化器的辅助序列化器，用于给出简略的用户序列化(id+username)
    """
    id = serializers.ReadOnlyField()
    username = serializers.ReadOnlyField()

    class Meta:
        model = ProjUser
        fields = ('id', 'username')


class ProjUserGroupDetailSerializer(serializers.ModelSerializer):
    creator = serializers.ReadOnlyField(source='creator.username')
    creator_id = serializers.ReadOnlyField(source='creator.id')
    members = GroupUserSerializer(many=True, read_only=True)
    question_groups = QuestionGroupSerializer(many=True, read_only=True)


    class Meta:
        model = ProjUserGroup
        fields = '__all__'

class QuestionGroupUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = QuestionGroup
        fields = ['authority', 'describe', 'name', 'questions', 'user_groups']

